let noticeDao = module.exports;
let util = require('util');
let mysqlPool = require('./MySQLPool');

noticeDao.save = async function (notice) {
    let sql = 'insert into notice (title, author, author_name, content, category, is_top, create_time, update_time, to_uid)' +
        '                  values (?,     ?,      ?,           ?,       ?,        ?,      now(),       now(),        ?)';
    let args = [notice.title, notice.author, notice.authorName, notice.content, notice.category, notice.isTop, notice.toUid];
    let res = await mysqlPool.query(sql, args);
    if (res){
        return res.insertId;
    }

    return 0;
};

noticeDao.queryPage = async function(cond){
    if (!cond.page) cond.page = 1;
    if (!cond.count) cond.count = 10;
    cond.page = parseInt(cond.page);
    if (cond.page <= 0) cond.page = 1;
    cond.count = parseInt(cond.count);
    if (cond.count <= 0) cond.count = 10;

    let cntSql = 'select count(1) cnt from notice where (to_uid = ? or to_uid = -1)';
    let cntArgs = [cond.uid];
    if (cond.author){
        cntArgs.push(cond.author);
        cntSql += ' and author = ?';
    }

    if (cond.isTop) {
        cntArgs.push(cond.isTop);
        cntSql += ' and is_top = ?';
    }

    let cntRes = await mysqlPool.query(cntSql, cntArgs);
    if (!cntRes) {
        return {cnt: 0, res:[]};
    }

    let sql = 'select * from notice where (to_uid = ? or to_uid = -1) ';
    let args = [cond.uid];
    if (cond.author){
        cntArgs.push(cond.author);
        cntSql += ' and author = ?';
    }

    if (cond.isTop) {
        cntArgs.push(cond.isTop);
        cntSql += ' and is_top = ?';
    }

    sql += ' order by is_top desc, create_time desc limit ?, ?';
    args.push((cond.page - 1) * cond.count);
    args.push(cond.count);
    let res = await mysqlPool.query(sql, args);
    if (res){
        return {cnt: cntRes[0].cnt, res:res};
    }

    return {cnt: 0, res:[]};
};

noticeDao.get = async function(id){
    let sql = 'select * from notice where id = ? limit 1';
    let args = [id];
    let res = await mysqlPool.query(sql, args);
    if (res){
        return res[0];
    }

    return null;
};

noticeDao.setTop = async function(id, isTop){
    if (!isTop) isTop = 0;
    isTop = parseInt(isTop);
    if (isTop !== 0 && isTop !== 1) isTop = 0;

    let sql = 'update notice set is_top = ? where id = ?';
    let args = [isTop, id];
    let res = await mysqlPool.query(sql, args);
    if (res){
        return res.affectedRows;
    }

    return 0;
};
